jpackage( "twc.account.models", function(){
	this.TabsData = Backbone.Model.extend({
		defaults: {
			StatementDetails : null,
			RecentActivity: null
		},

		// Remove this Todo from *localStorage* and delete its view.
		clear: function() {
			this.destroy();
		}
	});

	this.Charge = Backbone.Model.extend({
		defaults: {
			date: "10/11",
			description: "Default charge",
			amount: 0
		},

		initialize: function() {
			//TODO format date time string if necessary
			if (!this.get('amount')) {
				this.set('amount', this.defaults.amount);
			}
			var amountDisplay = parseFloat(this.get('amount')).toFixed(2);
			this.set('amountDisplay', amountDisplay);
		},

		// Remove this Todo from *localStorage* and delete its view.
		clear: function() {
			this.destroy();
		}
	});
});

jpackage( "twc.account.collections", function(){
	this.Charges = Backbone.Collection.extend({
		// Reference to this collection's model.
		model : twc.account.models.Charge,
		comparator : function(charge) {
			return charge.date;
		},

		amountTotal: function() {
			var amountTotal = this.reduce(function(memo, charge) { return memo + parseFloat(charge.get('amount')) }, 0);
			return amountTotal;
		}
	});
});
jpackage( "twc.account.views", function(){
	this.AccountTabs = Backbone.View.extend({
		initialize: function() {
			//initialize tabs
			this.$el = $(this.el);
			this.$detailsTab = this.$el.find('.details-tab');

            this.model.on('change', this.render, this);
		},
		render: function() {
			//get data
			var details = this.model.get('StatementDetails');

			this.statementDetails = new twc.account.views.StatementDetails(details);

			this.renderTab(this.$detailsTab, this.statementDetails, details);
		},
		renderTab: function($tab, subview, data) {
			if (data === null) {
				$tab.hide();
			} else {
				subview.render();
			}
		}
	});
	
	this.ChargeRow = Backbone.View.extend({
		tagName: 'tr',
		model : twc.account.models.Charge,
		render: function() {
			var $el = $(this.el);
			var template = twc.utils.template('charge-template');

			$el.html(template(this.model.attributes));

			return this;
		}
	});

	this.StatementDetails = Backbone.View.extend({
		el: $("#statement-details"),

		initialize: function(detailsData) {
			//set the two tables, and the total cell
			this.$chargesTable = this.$("#statement-charges");
			this.$feesTable = this.$("#statement-fees");
			this.$totalCell = this.$("#statement-total-cell");

			//load data
			this.feeCollection = new twc.account.collections.Charges(detailsData.fees);
			this.chargeCollection = new twc.account.collections.Charges(detailsData.charges);
		},

		render: function() {
			this.renderTable(this.chargeCollection, this.$chargesTable, this.addChargeRow);
			this.renderTable(this.feeCollection, this.$feesTable, this.addFeeRow);

			var detailTotal = this.feeCollection.amountTotal() + this.chargeCollection.amountTotal();
			this.$totalCell.html("$" + detailTotal.toFixed(2));
		},
	
		renderTable : function(collection, $table, callback) {
			if (collection.length === 0) {
				$table.hide();
			} else {
				collection.each(callback, this);
			}
		},
		addChargeRow: function(charge) {
			var view = new twc.account.views.ChargeRow({model: charge});
			this.$chargesTable.append(view.render().el);
		},
		addFeeRow: function(fee) {
			var view = new twc.account.views.ChargeRow({model: fee});
			this.$feesTable.append(view.render().el);
		}
	});
});




jpackage( "twc.account.billing", function(){
	var blurDropDown = $('html').hasClass('lt-ie9');

	var CookieUtil = twc.utils.CookieUtil;
	var BillingAppUrl = Backbone.Model.extend({
		url : "/myservices/account/api_obpUrl",
		//url : "/myservices/account/getBillPayUrl",
		//url : "/myservices/account/billpaydemo",
		defaults : {
			paymentMethod : 'cardonetime',
			statementCode : '1',
			tcVersion: null,
			multipleStatements: false
		},
		initialize : function(obj) {

			this.url = this.url + "?statementCode=" + obj.statementCode + "&paymentMethod=" + obj.paymentMethod 
						+ "&tcVersion=" + obj.tcVersion + "&showStatement=" + obj.showStatement;
		}
	});
	var BillingType = Backbone.View.extend({
		el : '.billing-type-wrapper',
		header : '.billpay-header',
		termsContainer : '#billing-terms-container',
		termsControlsContainer : '#billing-terms-container .next-step-container',
		typeContainer : '#billing-type-container',

		paymentType : 'input[name="payment-type"]:checked',
		cardPaymentOneTime : 'input#cardonetime',
		cardPaymentRecurring : 'input#cardreoccurring',
		
		recurringContainer : 'div.recurring .pay-with',
		oneTimeContainer : 'div.one-time .pay-with',

		agreeTermsButton : 'a#agree-terms',
		cancelButton : 'a.cancel-link',
		termsUncheckedError : '.terms-unchecked-error',
		
		tcVersion : null,

		events : {
			'click a#confirm-billpay-type' : 'showTerms',
			'click a#agree-terms' : 'agreeTerms',
			'click a#print-billing-terms' : 'printTerms',
			'change input[name="payment-period"]': 'changeType',
			'change input#agree-terms-checkbox' : 'toggleTermsButton'
		},

		agreeTerms : function(event) {
			if ($(this.agreeTermsButton).hasClass('disabled')) {
				$(this.termsUncheckedError).show();
				return;
			}

			//hide cancel link as it can cause problems with transition if they cancel now
			$(this.cancelButton).hide();

			//add transition button
			twc.utils.setLoader(event.target);
			//call parent
			this.parent.showBillingApp(this.getType(), this.getTCVersion());
		},
		changeType : function(event) {

            $(this.recurringContainer).toggleClass('disabled');
			$(this.oneTimeContainer).toggleClass('disabled');

			if (event.target.id == "recurring-option") {
                $(this.cardPaymentRecurring).attr('checked', true);

				$(this.oneTimeContainer).find('input').attr('disabled', true);
				$(this.recurringContainer).find('input').removeAttr('disabled');

            } else {
                $(this.cardPaymentOneTime).attr('checked', true);

				$(this.recurringContainer).find('input').attr('disabled', true);
				$(this.oneTimeContainer).find('input').removeAttr('disabled');
			}

		},
		getTCVersion : function() {
			return this.tcVersion;
		},
		getType : function() {
			return $(this.paymentType).attr('data-payment-type');
		},
		hide : function() {
			this.$el.hide();
		},
		initialize : function(args) {
			this.parent = args.parent;
			this.$el = $(this.el);
			this.$typeContainer = $(this.typeContainer);
			this.$termsContainer = $(this.termsContainer);
			this.$termsControlsContainer = $(this.termsControlsContainer);


		},
		printTerms : function () {
			twc.print.view.render($('div.terms:visible').html());
		},
		render : function() {
			this.$el.show();
			this.$typeContainer.show();
			this.$termsContainer.hide();
            // This always makes sure that the radio buttons are set back to default by reloading the template.
            var template = _.template( $("#payment-content-template").html() );
            $('#payment-holder').html(template());

		},
		showTerms : function(event) {
			this.$typeContainer.hide();
			this.$termsContainer.show();
			this.$termsContainer.removeClass();

			var type = this.getType();
			this.$termsContainer.addClass(type);
			this.tcVersion = $('div.terms:visible').attr('data-version');

            var html = twc.utils.template('billing-terms-controls')();
			this.$termsControlsContainer.html(html);

            /* omni tracking */
            var user = twc.omniture.getUser().replace(/[|]/g,' > ').replace('one time', this.getType()).replace('unknown', 'payment type');
            var props = {"eVar2": user};
            twc.omniture.track('page', null, props);

		},
		toggleTermsButton : function(event) {
			$(this.agreeTermsButton).toggleClass('disabled');
			if (!$(this.agreeTermsButton).hasClass('disabled')) {
				$(this.termsUncheckedError).hide();
			}
		}
	});

	var BillPayApp = Backbone.View.extend({
		el : '#billing-app-container',

		events : {
			'click a.cancel-link' : 'cancelBillPay'
		},
		cancelBillPay : function() {
			this.hide();
			this.parent.showSummary();
		},
		initialize : function(args) {
			this.parent = args.parent;
			this.$el = $(this.el);

			this.statementCode = this.statementCode || this.$el.data('statement-code');
			this.multipleStatements = this.multipleStatements || this.$el.data('multiple-statements');
		},
		loaded : function(paymentType) {

		},
		buildIframe : function(url) {
			//only do this if cancel hasn't been clicked yet
			if (this.parent.isCancelled()) { return; }
			//set hard code the resize if we couldn't set the domain
			this.iframe = $('<iframe class="obpIframe" frameBorder="0"></iframe>').attr('src', url);

			this.iframe.load(_.bind(function() {
				if (this.parent.isCancelled()) { return; }

				this.parent.hideTerms();
				$(this.el).show();

				//this.resizeApp(345);
			}, this));

			$(this.el).html(this.iframe);
		},
		render : function(paymentType, tcVersion) {
			this.model = new BillingAppUrl({
				paymentMethod : paymentType, 
				statementCode : this.statementCode,
				tcVersion: tcVersion,
				showStatement: this.multipleStatements
			});

			this.model.fetch({
				success : _.bind(function(obj, urlObj) {
                    var timestamp = '&timestamp='+ new Date().getTime();
                    var url = urlObj.targetUrl + timestamp + '#' + encodeURIComponent( document.location.href);

                    /* IMPORTANT ONLY USE BELOW URL FOR TESTING OBP APP WITHIN MYS LOCALLY. REMOVE BEFORE POSTING TO GITHUB OR STAGING */
                    //url = "http://payment-dev.webapps.rr.com:8090/obp/?cstToken=o2i2hzZpYqPwpW6SlSc3%2FNCjC0emISsXGgESQj6yLYaSFk1toaYQSpxKMKvRybxIQzvn7k9tU2J6jBaSfRGo0pyJze4y6g4DS%2B4rnkt0%2FCbOMlJAHAGSUy7iTnaw1ZJ%2FJohLOgzrmRV8osoCTbHaqbjepucfgeyl3ezhQIb5c4gB%2BwU6OGM%2B9hjInslU4FpROTePGINgE8B0kIyn1RnSE%2Fn%2BfAE2aKERDpirmZLTKAFdIxiPcPhxyAJs%2FDTsQf8pckc27u7FP%2FIUH%2BuyWkxtXbIYV5c5RQYj&paymentMethod=cardonetime" + '#' + encodeURIComponent( document.location.href);

                    this.buildIframe(url);
				}, this),
				error : _.bind(function(model, req) {
					twc.errors.view.render(twc.copy.get('account/obp-error-title'), twc.copy.get('account/obp-error-body'));
					
					this.parent.cancelBillPay();
				}, this)
			});
		},
		resizeApp : function(height) {
            $(".obpIframe").height( height + 5 ) ;
		},

//        resizeApp : function(hardcoded) {
//            var domFrame = this.iframe.get(0);
//            if (domFrame.contentWindow && domFrame.contentWindow.document) {
//                domFrame.style.height = ($(domFrame.contentWindow.document.body).height()+100) + 'px';
//            }
//        },

		hide : function() {
			this.$el.hide();
		},
		
		scrollTo: function( pos ){
			var mainTop = $('#account-billing-wrapper').offset().top;
			pos = $.isNumeric(pos) ? mainTop + parseInt(pos) : $("#mys-page .container").offset().top;
			$("html,body").animate({ scrollTop: pos }, 250);
		}
	});

	this.AccountBilling = Backbone.View.extend({
		el : '#account-billing-wrapper',
		summaryContainer : '#account-summary-container',
		statementDropDown : 'select#pdf',
		spinner: '.view-statement .spinner',
		paperlessTab : '#account-tabs a[href="#statement-preferences"]',
		statementPreferences : "#statement-preferences",

		events : {
			'click a#start-pay-bill' : 'showBillingType',
			'click a.cancel-link' : 'cancelBillPay',
			'click .download-statement' : 'downloadStatement',
			'click .statement-go-paperless' : 'showPaperlessTab',
            'click #breadcrumbs a' : 'breadcrumbChange',
			'mousedown select#pdf' : 'selectDown',
			'change select#pdf': 'changeDown'
		},

		cancelBillPay : function() {
			this.billingTypeView.hide();
			this.appView.hide();
			this.$summaryContainer.show();
		},
        startLiveChat : function() {
            $('#chat-post').submit();
        },
		hideTerms : function() {
			this.billingTypeView.hide();
		},
		isCancelled : function() {
			return this.$summaryContainer.is(':visible');
		},
		initialize : function() {
			this.$summaryContainer = $(this.summaryContainer);
			this.$statementDropDown  = $(this.statementDropDown);
			this.$spinner = $(this.spinner);
			this.billingTypeView = new BillingType({parent: this});
			this.appView = new BillPayApp({parent: this});

			this.$paperlessTab = $(this.paperlessTab);
            this.$statementPreferences = $(this.statementPreferences);

		},
		scrollTo : function( pos ){
			this.appView.scrollTo( pos );
		},
		reloadBillingHeader : function() {
			var infoHeader = $('#billing-info-header');
			$(document).off('change', '#statement');
			$('.statement-spinner').removeClass('hide');
			infoHeader.each(twc.ajaxLoader.fetchData);
		},
		resizeBillingApp : function(height) {
			this.appView.resizeApp(height);
		},
		refreshAll : function() {
			location.reload(true);
		},
		restartBilling : function() {
			this.cancelBillPay();
			this.showBillingType();
		},
		showBillingApp : function(paymentType, tcVersion) {
			this.appView.render(paymentType, tcVersion);
		},
		showBillingError : function(header, body, action) {
			twc.errors.view.render(header, body, action);
		},
		showBillingType : function(event) {
			this.$summaryContainer.hide();
			this.billingTypeView.render();
            $("a.cancel-link").show();
            /* omni tracking */
            var user = twc.omniture.getUser().replace(/[|]/g,' > ').replace('unknown', 'pay my bill');
            var props = {"eVar2": user, "eVar57":"ebpp:1:1:pay my bill", "eVar59":twc.omniture.config('pageName')};
            twc.omniture.track('page', 'ebpp pay my bill click', props);
		},
		showPaperlessTab : function(){
			if(!this.$statementPreferences.hasClass('active')){
				this.$paperlessTab.tab('show');
			}
			this.$paperlessTab[0].scrollIntoView(true);
		},
        breadcrumbChange : function(event){
            event.preventDefault();
        },
		downloadStatement : function() {
			var dropDown = this.$statementDropDown[0];
			var spinner = this.$spinner;

			var index = dropDown.selectedIndex;
			var stmt = dropDown[index];

			spinner.fadeIn();

			$.fileDownload(stmt.value, {
				failCallback: function(html, url) {
					var header = 'Statement Download Error';
					var lheader = header.toLowerCase();

					spinner.hide();

					twc.omniture.track('error', 'ebpp > '+ lheader, lheader);
					twc.errors.view.render(header, "We're sorry, we were unable to retrieve your statement. Please try again later.");
				},

				successCallback: function(html, url) {
					var pgName = 'ebpp:statement download';
					var stmtStr = (index < 1) ? 'current' : (index < 2) ? 'last month' : (index + 1) + 'months ago';

					spinner.fadeOut();

					twc.omniture.track('event', pgName, { e7: pgName +':'+ stmtStr, events: 'event48' });
				}
			});
			return false;
		},

		selectDown : function() {
			//console.log("open");
		},

		changeDown:function(){
			if (blurDropDown)
				this.$statementDropDown.blur();
		}
	});
});


jpackage('twc.account.payment', function(){
    var doc = $(document);
    var confirm   = '#payment-cancel-confirm';
    var container = '#billing-info-container';

    function show_confirm(){
        $(confirm).slideDown(200);
    }

    function hide_confirm(){
        $(confirm).slideUp(200);
    }

    function confirm_cancel(ev){
        var btn  = ev.target;
        var elem = $(confirm);
        var code = elem.data('statement-code');

        twc.utils.setLoader(btn);
        elem.find('a').hide();

        $.ajax(twc.routes.get('account/cancel-recurring'), {
            type: 'POST',
            data: { _method: 'DELETE', statementCode: code }
        }).always(function(){
            elem.hide().find('a').show();
            twc.utils.clearLoader(btn);

        }).done(function(){
            $(container).find('.info-row.last span').text('One Time');

            twc.omniture.track('event', { events: 'event48', e7: 'ebpp > recurring payment cancellation' });
        }).fail(function(resp){
			
			var errorTmpl =  twc.utils.template('data-error');
			var error = errorTmpl({ message: twc.copy.get('account/recurring-payment-error') });

			$( error ).insertAfter( elem.parent() );

            twc.omniture.track('error', 'ebpp > recurring payment cancellation > error');
        });
    };

    doc.on('click', confirm +' a', hide_confirm);
    doc.on('click', confirm +' button', confirm_cancel);

    doc.on('click', container +' a[data-payment-freq]', function(ev){
        var data = $(this).data('payment-freq');

        if (data == 'cancel') show_confirm();
        else if (data == 'edit') window.accountBilling.showBillingType();
    });
});

$(document).on('ajax.billing_info', function(){
    var PaperlessModel = Backbone.Model.extend({
        url: twc.routes.get('account/paperless'),

        isNew:function(){ return true; }
    });

    var BaseView = Backbone.View.extend({
		paperlessLinks : '.statement-go-paperless',
        initialize:function(){
            this.$el.addClass('fade');

            this.model.on('sync update', function(){
                if (this.visible()) this.show()
                else this.hide();
            }, this);
        },

        show:function(){
            this.$el.show().find('input').prop('checked', false);

            setTimeout(_.bind(function(){
                this.addClass('in');
            }, this.$el), 1);
        },
		showPaperlessLinks : function() {
			$(this.paperlessLinks).show();
		},
        hide:function(){
            this.$el.hide().removeClass('in');
        },
		hidePaperlessLinks : function() {
			$(this.paperlessLinks).hide();
		},
        printOption:function(isActive){
            var print_button = $('#paperless-printable');
            (isActive) ? print_button.show() : print_button.hide();
        }
    });

    var PaperlessView = BaseView.extend({
        visible:function(){
            return this.model.get('isPaperless') === true;
        },

        events: {
            'click a.mys-btn':function(ev){
                var btn = $(ev.target);
                if (this.$el.find('input').is(':checked')){
                    twc.utils.setLoader(btn);
					var showLinks = _.bind(this.showPaperlessLinks,this);
			
                    this.model.set({ isPaperless: false });
                    this.model.save().always(function(){
                        twc.utils.clearLoader(btn);
						showLinks();
                    });
                }
            }
        }
    });

    var PaperfullView = BaseView.extend({
        visible:function(){
            return !this.model.confirming && this.model.get('isPaperless') === false;
        },

        events: {
            'click a.go-paperless-link':function(){
                this.printOption(true);
                this.model.confirming = true;
                this.model.trigger('update');
            }
        }
    });

    var ConfirmView = BaseView.extend({
        visible:function(){
            return !!this.model.confirming;
        },

        clear:function(){
            delete this.model.confirming;
        },

        events: {
            'click a.cancel':function(){
                this.printOption(false);
                this.clear();
                this.model.trigger('update');
            },

            'click button':function(ev){
                var el = ev.target;

                if (this.$el.find('input').is(':checked')){
                    twc.utils.setLoader(el);
                    this.printOption(false);
					var hideLinks = _.bind(this.hidePaperlessLinks, this);
                    this.model.save({ isPaperless: true }).always(function(){
                        twc.utils.clearLoader(el);
						hideLinks();
                    });
					
                    this.clear();
                }
            }
        }
    });

    var BenefitView = BaseView.extend({
        visible:function(){
            return !this.model.confirming;
        }
    });

    var el = $('#go-paperless-container');

	//el isn't always there
	if (el.length) {
		setupPaperless();
	}

	function setupPaperless() {
		var model = new PaperlessModel({
			isPaperless: el.data('state')
		});

		var statementCode = el.data('statement-code').toString();
		if (statementCode.length > 0) {
			model.set({statementCode: statementCode});
		}

		_.each({
			'.paperless': PaperlessView,
			'.paperfull': PaperfullView,
			'.paperless-confirm': ConfirmView,
			'.paperless-benefits': BenefitView
		}, function(obj, selector){
			new obj({ model: model, el: el.find(selector) });
		});

		model.set('isPaperless', el.data('state')).trigger('sync');

		// setup tracking
		model.on('sync', function(model){
			var name, opts;

			if (model.get('isPaperless')){
				name = 'ebpp:go paperless';
				opts = { events: 'events64' };
			} else {
				name = 'ebpp:paperless cancellation';
				opts = { events: 'event48', e7: name };
			}

			twc.omniture.track('event', name, opts);

		}).on('error', function(model, resp){
			twc.utils.renderRequestError(resp, el.parents('.shadow-inner'));
			twc.omniture.track('error', 'ebpp:go paperless:error');
		});

		$('a#paperless-printable').click(function() {
			if (model.confirming) {
				var termsContainer = $('.paperless-confirm pre');
				twc.print.view.render("<pre>"+termsContainer.html()+"</pre>");
			}
		}).hide();
	}
});

$(document).on('ajax.billing_info', function(){
	var omniName = 'ebpp > go paperless popup';
	var omniOpts = { p29: 'en-us', e29: 'en-us' };

	var ModalState = Backbone.Model.extend({
		shownCookie : 'paperlessShown',
		shownCountCookie : 'paperlessShownCount',
		maxShowCount: 5,
		needToShow: false,
		initialize : function() {
			this.shown = twc.utils.CookieUtil.read(this.shownCookie);
			this.shownCount = parseInt(twc.utils.CookieUtil.read(this.shownCountCookie), 10);

			if ((!this.shownCount || this.shownCount < this.maxShowCount) 
					&& this.shown == "" && this.get('qualified')) {
				this.needToShow = true;
			}
		},
		modalShown : function() {
			this.shownCount = this.shownCount ? this.shownCount+1 : 1;
			twc.utils.CookieUtil.write(this.shownCountCookie, this.shownCount + "");
			twc.utils.CookieUtil.write(this.shownCookie, '1')
		},
		need : function() {
			return this.needToShow;
		}
	});
	var PaperlessModal = Backbone.View.extend({
		el: "#paperless-modal",
		statementPreferences : "#statement-preferences",
		paperlessTab : '#account-tabs a[href="#statement-preferences"]',
		events : {
			'click button' : 'showGoPaperless',
			'click a': 'onHide'
		},
		showStateAttr : 'data-show-state',
		initialize : function() {
			this.$el = $(this.el);
            this.$statementPreferences = $(this.statementPreferences);
			this.$paperlessTab = $(this.paperlessTab);

			this.model = new ModalState({
				qualified: $(this.el).attr(this.showStateAttr) === 'true'
			});
			
			if (this.model.need()) {
				this.model.modalShown();
				this.$el.modal();
			}
		},

		trackOmni:function(ps){
			var props = _.extend({ e17: 'go_paperless_' + (ps ? 'yes' : 'no') }, omniOpts);

			twc.omniture.track('event', omniName, props);
		},

		showGoPaperless : function() {
			this.$el.modal('hide');
			if(!this.$statementPreferences.hasClass('active')){
				this.$paperlessTab.tab('show');
			}

			this.$paperlessTab[0].scrollIntoView(true);
			this.trackOmni(true);
		},

		onHide:function(){
			this.trackOmni(false);
		}
	});
	var modal = new PaperlessModal();
});

jpackage('twc.account.summary', function(){
    var doc = $(document);

    function switchStatement(e){
        var infoHeader = $('#billing-info-header');
        doc.off('change', '#statement');
        $('.statement-spinner').removeClass('hide');
        infoHeader.data('ajax-url',(twc.routes.get('account/ajax_billing_info',{s:$(e.target).val()})));
        infoHeader.each(twc.ajaxLoader.fetchData);

    }

    doc.bind('pre_ajax.billing_info', function(e){
        var accBilling = $('#account-billing');
        if(accBilling.length > 0){
            accBilling.remove();
            $('#account-billing-wrapper').remove();
        }

    });

    doc.bind('ajax.billing_info', function(e){
        doc.on('change', '#statement', switchStatement);
    });

});

(function(appointments){
    var appts = new appointments.Collection();
    var view = new appointments.ResultView({
        appointments: appts, account: true, el: '#appointments'
    });


    // for omniture
    appts.on({
        reset:function(c){
            var props = { e66: 'Logged In: ' };

            props.e66 += (c.length ? '' : 'No ') +'Appointment Present';

            this.track('event', props);
        }
    }, twc.omniture);
    appts.fetch();

}(twc.appointments));

$(document).on('ajax.billing_info', function() {
    //make fake data for statement charges, fees, etc.
    var FakeStatementData = {
        charges : [
            {
            date : '10/15 - 11/15',
            description : 'TWC Local Basic',
            amount : '4'
        },
        {
            date : '10/15 - 11/15',
            description : 'TWC Expandable Cable',
            amount : '3'
        },
        {
            date : '10/15 - 11/15',
            description : 'DVR Service',
            amount : '8'
        }
        ],
        fees : [
            {
            'date' : '10/15 - 11/15',
            'description' : 'State Sales Tax - Equip',
            'amount' : '7.683'
        },
        {
            'date' : '9/15',
            'description' : 'Franchise Fee',
            'amount' : '96.37'
        },
        {
            'date' : '9/15',
            'description' : 'State Sales Tax - Cable',
            'amount' : '576.13'
        }
        ]
    };

    // Set up account view
    var tabsModel = new twc.account.models.TabsData();
    var tabsView = new twc.account.views.AccountTabs({model: tabsModel, el: '#account-tabs'});
    var tabsData = { StatementDetails : FakeStatementData };

    tabsModel.set(tabsData);

    window.accountBilling = new twc.account.billing.AccountBilling();

	if (window.location.hash.indexOf('#show-billing-app') !== -1) {
		window.location.hash = "";
		window.accountBilling.showBillingType();
	}
});

$(document).on('ajax.services', function(){
	var start = window.location.hash.indexOf("troubleshoot") !== -1;
    var equipment = new twc.account.equipment.views.Equipment({ el: $('#account-equipment-tab')[0], autoStart : start });

	$(document).on('click', "#error-modal a.expand-troubleshoot", function() {
		equipment.expandTroubleshootingTips();
	});

    // setup tooltips
    $("ul.equipment-list .details").each(function() {
        var elem = $(this);
        var content = elem.find('.equipment-tooltip-content').html();

		if ($(".troubleshootEnabled").length) {
			elem = $(this).find('.device-make');
		}

		var placement = "right";
		var template = '<div class="tooltip equipment-tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>';

		if ($(window).width() <= 400) {
			placement = "bottom";
			template = '<div class="tooltip equipment-tooltip popover"><div class="arrow"></div><div class="tooltip-inner"></div></div>';
		}

 	    elem.tooltip({'title' : content, 'placement' : placement, template: template });
    });
});



$(function(){
    var domain = twc.routes.get("obpURL");
    domain = domain.substring(0, domain.lastIndexOf("/obp"));

    /* IMPORTANT ONLY USE BELOW URL FOR TESTING OBP APP WITHIN MYS LOCALLY. REMOVE BEFORE POSTING TO GITHUB OR STAGING */
    //domain= "http://payment-dev.webapps.rr.com:8090"

    $.receiveMessage(function(e){

        var params = e.data.split("&");
        var result = {};
        for (var i = 0; i < params.length; i++){
            var tmp = params[i].split("=");
            result[tmp[0]] = unescape(tmp[1]);
        }

        var method = result['method'];

        switch(method){
            case 'trackObp' :
                var msg = twc.utils.Base64Util.decode( decodeURIComponent( result['message']  ) );
                var props = $.parseJSON(msg);
                var type = props.type;
                delete props.type;
                if(type == "page"){
                   twc.omniture.track('page', props.pageName, props);
                }else{
                   twc.omniture.track('event', props);
                }
                break;
            case 'height' :
                var h = Number( e.data.replace( /.*height=(\d+)(?:&|$)/, '$1' ) );
                if ( !isNaN( h ) && h > 0) {
                    window.accountBilling.appView.resizeApp(h);
                }
                break;
            case 'cancel' :
                window.accountBilling.cancelBillPay();
                break;
            case 'return' :
                window.accountBilling.cancelBillPay();
                window.accountBilling.reloadBillingHeader();
                break;
            case 'liveChat' :
                window.accountBilling.startLiveChat();
                break;
            case 'showBillingError' :
                var msg =  twc.utils.Base64Util.decode( decodeURIComponent( result['message']  ) );
                msg = $.parseJSON(msg);
                var messArr = msg.split("|");
                var body = "<div>";
                for(var it = 0; it < messArr.length; it ++){
                   body += "<li>"+messArr[it]+"</li>"
                }
                body += "</div>";
                window.accountBilling.showBillingError("Alert", body);
                break;
			case 'scrollBillingTo' :
				var pos = result['message'];
				window.accountBilling.scrollTo( pos );
				break;
			case 'restart' :
				window.accountBilling.restartBilling();
				break;
        }

        // An optional origin URL (Ignored where window.postMessage is unsupported).
    }, domain );
});

(function(){
    var doc = document;
    var activeSet = false;

    var hash  = unescape(location.hash.substr(1));
    var parts = hash.split('/');

    function byHref(href){
        return function(){
            return $(this).attr('href') == href;
        };
    };

    if (parts[0] == 'jmp' && parts[1]){
        var el = $( doc.getElementById('account-'+ parts[1]) );

        $(doc).on('ajax.complete', function(){
            $('html,body').animate({ scrollTop: el.offset().top }, function(){
                if (!activeSet && parts[2]){
                    // click the equipment tab
                    el.find('.service-tabs a').filter(byHref('#account-equipment-tab')).click();

                    // click specific product tab (unless TV)
                    if (parts[2] != 'tv'){
                        el.find('.nav-tabs a').filter(byHref('#equipment-'+ parts[2] +'-tab')).click();
                    }

                    activeSet = true;
                }
            });
        });
    }
}());

/*!
 * jQuery postMessage - v0.5 - 9/11/2009
 *                      v0.6 (TWC) 8/10/2011
 * http://benalman.com/projects/jquery-postmessage-plugin/
 *
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

/**
 * @fileOverview
 * @version: 0.6, Last updated: 8/10/2011*
 *
 <pre>
 jQuery postMessage - v0.5 - 9/11/2009
 v0.6 (TWC) 8/10/2011
 http://benalman.com/projects/jquery-postmessage-plugin/

 Copyright (c) 2009 "Cowboy" Ben Alman<br/>
 Dual licensed under the MIT and GPL licenses.
 http://benalman.com/about/license/

 Script: jQuery postMessage: Cross-domain scripting goodness<br/>


 Project Home - http://benalman.com/projects/jquery-postmessage-plugin/
 GitHub       - http://github.com/cowboy/jquery-postmessage/
 Source       - http://github.com/cowboy/jquery-postmessage/raw/master/jquery.ba-postmessage.js
 (Minified)   - http://github.com/cowboy/jquery-postmessage/raw/master/jquery.ba-postmessage.min.js (0.9kb)

 About: License

 Copyright (c) 2009 "Cowboy" Ben Alman,
 Dual licensed under the MIT and GPL licenses.
 http://benalman.com/about/license/

 About: Examples

 This working example, complete with fully commented code, illustrates one
 way in which this plugin can be used.

 Iframe resizing - http://benalman.com/code/projects/jquery-postmessage/examples/iframe/

 About: Support and Testing

 Information about what version or versions of jQuery this plugin has been
 tested with and what browsers it has been tested in.

 jQuery Versions - 1.3.2, 1.5
 Browsers Tested - Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 10.

 About: Release History

 0.6 - (8/10/2011) Use native postMessage for Opera browser (Heidi Hunter - TWC)
 0.5 - (9/11/2009) Improved cache-busting
 0.4 - (8/25/2009) Initial release
 </pre>
 */
(function($){
    '$:nomunge'; // Used by YUI compressor.

    // A few vars used in non-awesome browsers.
    var interval_id,
        last_hash,
        cache_bust = 1,

    // A var used in awesome browsers.
        rm_callback,

    // A few convenient shortcuts.
        window = this,
        FALSE = !1,

    // Reused internal strings.
        postMessage = 'postMessage',
        addEventListener = 'addEventListener',

        p_receiveMessage,

        has_postMessage = window[postMessage];

    // Method: jQuery.postMessage
    //
    // This method will call window.postMessage if available, setting the
    // targetOrigin parameter to the base of the target_url parameter for maximum
    // security in browsers that support it. If window.postMessage is not available,
    // the target window's location.hash will be used to pass the message. If an
    // object is passed as the message param, it will be serialized into a string
    // using the jQuery.param method.
    //
    // Usage:
    //
    // > jQuery.postMessage( message, target_url [, target ] );
    //
    // Arguments:
    //
    //  message - (String) A message to be passed to the other frame.
    //  message - (Object) An object to be serialized into a params string, using
    //    the jQuery.param method.
    //  target_url - (String) The URL of the other frame this window is
    //    attempting to communicate with. This must be the exact URL (including
    //    any query string) of the other window for this script to work in
    //    browsers that don't support window.postMessage.
    //  target - (Object) A reference to the other frame this window is
    //    attempting to communicate with. If omitted, defaults to `parent`.
    //
    // Returns:
    //
    //  Nothing.

    $[postMessage] = function( message, target_url, target ) {
        if ( !target_url ) { return; }

        // Serialize the message if not a string. Note that this is the only real
        // jQuery dependency for this script. If removed, this script could be
        // written as very basic JavaScript.
        message = typeof message === 'string' ? message : $.param( message );

        // Default to parent if unspecified.
        target = target || parent;

        if ( has_postMessage ) {
            // The browser supports window.postMessage, so call it with a targetOrigin
            // set appropriately, based on the target_url parameter.
            target[postMessage]( message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1' ) );

        } else if ( target_url ) {
            // The browser does not support window.postMessage, so set the location
            // of the target to target_url#message. A bit ugly, but it works! A cache
            // bust parameter is added to ensure that repeat messages trigger the
            // callback.
            target.location = target_url.replace( /#.*$/, '' ) + '#' + (+new Date) + (cache_bust++) + '&' + message;
        }
    };

    // Method: jQuery.receiveMessage
    //
    // Register a single callback for either a window.postMessage call, if
    // supported, or if unsupported, for any change in the current window
    // location.hash. If window.postMessage is supported and source_origin is
    // specified, the source window will be checked against this for maximum
    // security. If window.postMessage is unsupported, a polling loop will be
    // started to watch for changes to the location.hash.
    //
    // Note that for simplicity's sake, only a single callback can be registered
    // at one time. Passing no params will unbind this event (or stop the polling
    // loop), and calling this method a second time with another callback will
    // unbind the event (or stop the polling loop) first, before binding the new
    // callback.
    //
    // Also note that if window.postMessage is available, the optional
    // source_origin param will be used to test the event.origin property. From
    // the MDC window.postMessage docs: This string is the concatenation of the
    // protocol and "://", the host name if one exists, and ":" followed by a port
    // number if a port is present and differs from the default port for the given
    // protocol. Examples of typical origins are https://example.org (implying
    // port 443), http://example.net (implying port 80), and http://example.com:8080.
    //
    // Usage:
    //
    // > jQuery.receiveMessage( callback [, source_origin ] [, delay ] );
    //
    // Arguments:
    //
    //  callback - (Function) This callback will execute whenever a <jQuery.postMessage>
    //    message is received, provided the source_origin matches. If callback is
    //    omitted, any existing receiveMessage event bind or polling loop will be
    //    canceled.
    //  source_origin - (String) If window.postMessage is available and this value
    //    is not equal to the event.origin property, the callback will not be
    //    called.
    //  source_origin - (Function) If window.postMessage is available and this
    //    function returns false when passed the event.origin property, the
    //    callback will not be called.
    //  delay - (Number) An optional zero-or-greater delay in milliseconds at
    //    which the polling loop will execute (for browser that don't support
    //    window.postMessage). If omitted, defaults to 100.
    //
    // Returns:
    //
    //  Nothing!

    $.receiveMessage = p_receiveMessage = function( callback, source_origin, delay ) {
        if ( has_postMessage ) {
            // Since the browser supports window.postMessage, the callback will be
            // bound to the actual event associated with window.postMessage.

            if ( callback ) {
                // Unbind an existing callback if it exists.
                rm_callback && p_receiveMessage();

                // Bind the callback. A reference to the callback is stored for ease of
                // unbinding.
                rm_callback = function(e) {
                    if ( ( typeof source_origin === 'string' && e.origin !== source_origin )
                        || ( $.isFunction( source_origin ) && source_origin( e.origin ) === FALSE ) ) {
                        return FALSE;
                    }
                    callback( e );
                };
            }

            if ( window[addEventListener] ) {
                window[ callback ? addEventListener : 'removeEventListener' ]( 'message', rm_callback, FALSE );
            } else {
                window[ callback ? 'attachEvent' : 'detachEvent' ]( 'onmessage', rm_callback );
            }

        } else {
            // Since the browser sucks, a polling loop will be started, and the
            // callback will be called whenever the location.hash changes.

            interval_id && clearInterval( interval_id );
            interval_id = null;

            if ( callback ) {
                delay = typeof source_origin === 'number'
                    ? source_origin
                    : typeof delay === 'number'
                    ? delay
                    : 100;

                interval_id = setInterval(function(){
                    var hash = document.location.hash,
                        re = /^#?\d+&/;
                    if ( hash !== last_hash && re.test( hash ) ) {
                        last_hash = hash;
                        callback({ data: hash.replace( re, '' ) });
                    }
                }, delay );
            }
        }
    };

})(jQuery);

